package com.ideal.tools.ssh.operation.hive;

import com.ideal.tools.ssh.common.CommonProperties;
import com.ideal.tools.ssh.common.CommonTools;
import com.ideal.tools.ssh.context.ClusterContext;
import com.ideal.tools.ssh.entity.LinuxCommand;
import com.ideal.tools.ssh.operation.LinuxOperation;
import com.ideal.tools.ssh.result.LinuxResult;
import org.apache.commons.lang3.StringUtils;

/**
 * Created by CC on 2016/3/7.
 */
public class CreateSentryRole extends LinuxOperation {

    String superUser;
    String jdbc;
    String principal;
    String db_role;

    public CreateSentryRole(String db_role){
        this.db_role = db_role;
    }

    @Override
    public void execLinuxCMD(ClusterContext context) {
        this.superUser = context.getCommonProperties().getProperty(CommonProperties.HIVE_SUPER_USER,"hive");
        this.jdbc = context.getCommonProperties().getProperty(CommonProperties.HIVE_SENTRY_JDBC,"");
        this.principal = context.getCommonProperties().getProperty(CommonProperties.HIVE_SENTRY_PRINCIPAL,"");
//        this.db_role  = CommonTools.getHiveRole("db","all",role_path,context.getCommonProperties());

        //具体去运行的命令  这个地方 可能不灵活 如果需要修改命令 会需要修改代码
        //这里后面可以移动到从数据库中载入数据
        StringBuffer cmd=new StringBuffer() ;
        cmd.append("sudo -u "+superUser+" beeline -u ");
        cmd.append("\""+jdbc+";"+principal+"\" -e ");
        cmd.append("\"");
        cmd.append("create role "+db_role+";");
        //结束
        cmd.append("\"");

        //创建命令 创建命令的时候 需要根据不同的OperationType 初始化不同的参数
        setLinuxCommand(new LinuxCommand().initCMD(cmd.toString()));

        /**这个分割线是为了说明下面的是基本不用变的，如果要实现新的功能，只需要写上面**/

        //执行
        super.execOperation(context);
    }

    @Override
    public void setResultNote(LinuxResult linuxResult) {
//        String info = getResultInfo();
        int exitcode = linuxResult.getExitCode();
        String exitCodeMean="";
        String host=getHost();
        if(exitcode == 0){
            exitCodeMean = "SUCCESS Create HIVE Role! ["+db_role+"] ["+host+"]\n";
        }else if(exitcode==1){
            exitCodeMean = "HIVE Role ["+db_role+"]  EXIT! ["+host+"]\n";
            linuxResult.setSuccess(true);
        }else {
            exitCodeMean = "FAILD Create HIVE Role! ["+db_role+"] ["+host+"]\n";
            linuxResult.setSuccess(false);
        }
        //设置note
        linuxResult.setNote(exitCodeMean+(StringUtils.isBlank(linuxResult.getNote())?"":linuxResult.getNote()));
    }
}
